package org.csu.onlineedubackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.csu.onlineedubackend.dto.ForumFavoriteDTO;
import org.csu.onlineedubackend.entity.*;
import org.csu.onlineedubackend.mapper.*;
import org.csu.onlineedubackend.service.ForumFavoriteService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ForumFavoriteServiceImpl implements ForumFavoriteService {
    @Autowired
    private ForumFavoriteMapper forumFavoriteMapper;

    @Autowired
    private ForumPostMapper forumPostMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ForumLikeMapper forumLikeMapper;

    @Autowired
    private ForumCommentMapper forumCommentMapper;

    @Autowired
    private ForumNotificationMapper forumNotificationMapper;

    @Override
    public boolean favorite(Integer userId, Integer postId) {
        LambdaQueryWrapper<ForumFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumFavorite::getUserId, userId).eq(ForumFavorite::getPostId, postId);
        if (forumFavoriteMapper.selectCount(wrapper) > 0) {
            return false; // 已收藏
        }
        ForumFavorite favorite = new ForumFavorite();
        favorite.setUserId(userId);
        favorite.setPostId(postId);
        boolean ok = forumFavoriteMapper.insert(favorite) > 0;

        // 添加通知
        if (ok) {
            ForumPost post = forumPostMapper.selectById(postId);
            if (post != null && !post.getUserId().equals(userId)) {
                ForumNotification notif = new ForumNotification();
                notif.setUserId(post.getUserId()); // 接收者 = 帖子作者
                notif.setSenderId(userId);
                notif.setType(3); // 3 = 收藏
                notif.setTargetType(1); // 目標是帖子
                notif.setTargetId(postId);
                notif.setContent("您的帖子被收藏");
                notif.setIsRead(0);
                forumNotificationMapper.insert(notif);
            }
        }
        return ok;
    }

    @Override
    public boolean unfavorite(Integer userId, Integer postId) {
        LambdaQueryWrapper<ForumFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumFavorite::getUserId, userId).eq(ForumFavorite::getPostId, postId);
        return forumFavoriteMapper.delete(wrapper) > 0;
    }

    @Override
    public boolean isFavorited(Integer userId, Integer postId) {
        LambdaQueryWrapper<ForumFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumFavorite::getUserId, userId).eq(ForumFavorite::getPostId, postId);
        return forumFavoriteMapper.selectCount(wrapper) > 0;
    }

    @Override
    public List<ForumFavoriteDTO> getFavoritesByUser(Integer userId) {
        LambdaQueryWrapper<ForumFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumFavorite::getUserId, userId);
        wrapper.orderByDesc(ForumFavorite::getCreatedAt);
        List<ForumFavorite> favorites = forumFavoriteMapper.selectList(wrapper);
        
        return favorites.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public int getFavoriteCountByPost(Integer postId) {
        LambdaQueryWrapper<ForumFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ForumFavorite::getPostId, postId);
        return forumFavoriteMapper.selectCount(wrapper).intValue();
    }

    /**
     * 將實體轉換為DTO
     */
    private ForumFavoriteDTO convertToDTO(ForumFavorite favorite) {
        ForumFavoriteDTO dto = new ForumFavoriteDTO();
        BeanUtils.copyProperties(favorite, dto);

        // 獲取帖子信息
        ForumPost post = forumPostMapper.selectById(favorite.getPostId());
        if (post != null) {
            dto.setTitle(post.getTitle());
            dto.setContent(post.getContent());
            dto.setPostCreatedAt(post.getCreatedAt());

            // 獲取作者信息
            User author = userMapper.selectById(post.getUserId());
            if (author != null) {
                dto.setAuthorName(author.getUsername());
                dto.setAuthorAvatar(author.getAvatar());
            }

            // 獲取點贊和評論數
            LambdaQueryWrapper<ForumLike> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(ForumLike::getPostId, post.getId());
            dto.setLikeCount(forumLikeMapper.selectCount(likeWrapper).intValue());

            LambdaQueryWrapper<ForumComment> commentWrapper = new LambdaQueryWrapper<>();
            commentWrapper.eq(ForumComment::getPostId, post.getId())
                        .eq(ForumComment::getStatus, "active");
            dto.setCommentCount(forumCommentMapper.selectCount(commentWrapper).intValue());
        }

        return dto;
    }
} 